﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Principal;
using System.Web.Security;

public partial class WebControls_Login : System.Web.UI.UserControl
{
    int currentUserId;
    protected void Page_Load(object sender, EventArgs e)
    {
        String createUserUrl = "/Register.aspx";
        String passwordRecoveryUrl = "/ForgetPass.aspx";
        Login1.CreateUserUrl = createUserUrl;
        Login1.PasswordRecoveryUrl = passwordRecoveryUrl;
        if (!Page.IsPostBack)
        {
            LoadData();
        }

        Login1.UserNameLabelText = "Tên đăng nhập";
        Login1.PasswordLabelText = "Mật khẩu";
        Login1.FailureText = "Đăng nhập thất bại";
        Login1.CreateUserText = "Đăng kí tài khoản";
        Login1.PasswordRecoveryText = "Lấy lại mật khẩu";
    }

    protected void LoadData()
    {
        if (Context.User.Identity.IsAuthenticated)
        {
            if (Context.User.IsInRole(WebsiteConstant.ROLES_ADMINISTRATORS))
            {
                btnLogout.Visible = true;
            }
            else
            {
                btnLogout.Visible = true;

            }
        }

        if (!Context.User.Identity.IsAuthenticated)
        {
            LoginPanel.Visible = true;
            LoginMessagePanel.Visible = false;
        }
        else
        {
            LoginPanel.Visible = false;
            LoginMessagePanel.Visible = true;
            SetLabel();
            currentUserId = Utilities.CurrentUserID;


        }
    }

    protected void SetLabel()
    {
        lblHelloUser.Text = "Xin chào " + Utilities.CurrentUserName;
        btnLogout.ToolTip = "Đăng xuất";
    }

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        String username = Login1.UserName;
        String password = Login1.Password;

        bool remember = Login1.RememberMeSet;
        int userID;
        HttpCookie authCookie = LoginService.Authenticate(username, password, out userID);
        if (authCookie != null)
        {


            LoginMessagePanel.Visible = true;
            SetLabel();
            lblHelloUser.Text = "Xin chào " + username;
            // Store username in session
            Session.Add(WebsiteConstant.USER_NAME, username);
            // Add the cookie to the outgoing cookies collection.
            Response.Cookies.Add(authCookie);
            // Redirect the user to the originally requested page
            LoginPanel.Visible = false;
            string url = "~/Default.aspx";
            Response.Redirect(url);
        }
    }
    protected void btnLogout_Click(object sender, EventArgs e)
    {
        LoginService.SignOut();
        string url = "~/Default.aspx";
        Response.Redirect(url);
    }     
}